<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input v-model="q.keyword" style="margin-bottom:10px" type="text" prefix-icon="el-icon-search" size="small" placeholder="输入员工姓名全员搜索" @input="hSearch" />
        <!-- 树形组件
          default-expand-all 默认展开所有节点
          highlight-current 高亮当前节点
          :expand-on-click-node="false" 点击节点不展开, 只有点击三角箭头才展开
          node-key="id" 告诉树形组件, 将 id 设为唯一标识
         -->
        <el-tree
          ref="deptTree"
          :data="depts"
          :props="{ label: 'name' }"
          default-expand-all
          highlight-current
          :expand-on-click-node="false"
          node-key="id"
          @current-change="selectNode"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog = true">excel导入</el-button>
          <!-- 期望: 拥有 export 权限点的用户才可以看到这个按钮 -->
          <!-- v-if 可以实现功能, 但不方便复用, 而按钮级权限控制经常会用到, 所以要对其进行封装 -->
          <!-- <el-button v-if="$store.getters.userInfo?.roles?.points?.includes('export')" size="mini" @click="exportExcel">excel导出</el-button> -->
          <el-button v-perm="'export'" size="mini" @click="exportExcel">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table
          :data="list"
          :header-cell-style="{ background: '#f5f6f8', height: '60px' }"
        >
          <el-table-column label="头像" align="center">
            <template v-slot="{ row }">
              <el-avatar v-if="row.staffPhoto" :size="30" :src="row.staffPhoto" />
              <span v-else class="username">{{ row.username?.[0] }}</span>
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="手机号" sortable prop="mobile" />
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column label="聘用形式">
            <template v-slot="{ row }">
              {{ row.formOfEmployment === 1 ? '正式' : '非正式' }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <el-table-column label="操作" width="200px">
            <template v-slot="{ row }">
              <!-- 表格最右侧的三个按钮 -->
              <!--
                路由传参的两种方式:
                1. query 查询参数
                2. params 动态路由参数
               -->
              <el-button type="text" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button type="text" @click="openRoleDialog(row.id)">角色</el-button>
              <el-popconfirm title="确认删除吗?" class="el-button el-button--text" @confirm="hDel(row.id)">
                <el-button slot="reference" v-perm="'del-employee'" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row style="height: 60px" type="flex" justify="end" align="middle">
          <el-pagination
            :total="total"
            :current-page="q.page"
            :page-size="q.pagesize"
            layout="total, prev, pager, next"
            @current-change="hPageChange"
          />
        </el-row>
      </div>
    </div>
    <ImportExcel :show-excel-dialog.sync="showExcelDialog" @success="loadEmployees" />
    <el-dialog title="分配角色" :visible.sync="showRoleDialog">
      <!-- 复选框组, 勾选多个复选框, 可以将复选框的 label 双向绑定给数组 -->
      <el-checkbox-group v-model="checkList">
        <el-checkbox v-for="item in roles" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <!-- 确认取消按钮 -->
      <template #footer>
        <el-row type="flex" justify="center">
          <el-button size="mini" type="primary" @click="confirmAssign">确认</el-button>
          <el-button size="mini" @click="showRoleDialog = false">取消</el-button>
        </el-row>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getDepartments } from '@/api/department'
import { transListToTree } from '@/utils'
import { assignRoles, delEmployee, exportExcel, getEmployeeDetail, getEmployees } from '@/api/employee'
import fileSaver from 'file-saver'
import ImportExcel from './components/import-excel.vue'
import { getEnableRoles } from '@/api/role'
export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  data() {
    return {
      depts: [], // 左树
      q: {
        page: 1, // 当前页码数
        pagesize: 10, // 每页显示多少条
        keyword: '', // 搜索关键字
        departmentId: '' // 部门 id, 用于获取当前部门下的所有员工
      },
      list: [], // 右表
      total: 0,
      showExcelDialog: false,
      showRoleDialog: false, // 是否显示角色对话框
      checkList: [],
      roles: [], // 所有可用的角色列表
      currentId: ''
    }
  },
  created() {
    this.loadData()
  },
  methods: {
    async loadData() {
      // 加载树形数据
      // const res = await getDepartments()
      // console.log(transListToTree(res))
      this.depts = transListToTree(await getDepartments())
      // console.log(this.depts[0].id)
      // 获取第一个节点 id
      const id = this.depts[0].id
      // 存储到 departmentId 中
      this.q.departmentId = id
      // 选中节点
      // 由于数据设置后, DOM 更新是异步的, 所以必须要用 $nextTick()
      this.$nextTick(() => {
        this.$refs.deptTree.setCurrentKey(id)
      })

      // 获取员工列表
      this.loadEmployees()
    },
    async loadEmployees() {
      const { rows, total } = await getEmployees(this.q)
      this.list = rows
      this.total = total
    },
    selectNode(data) {
      // console.log(data)
      this.q.departmentId = data.id
      // 将页码值设置为 1 表示看第一页
      this.q.page = 1
      // 重新发请求获取员工列表
      this.loadEmployees()
    },
    hPageChange(page) {
      // console.log(page)
      this.q.page = page
      this.loadEmployees()
    },
    hSearch() {
      clearTimeout(this.timerId)
      this.timerId = setTimeout(() => {
        // 将页码值设置为 1 表示看第一页
        this.q.page = 1
        // 重新发请求获取员工列表
        this.loadEmployees()
      }, 500)
    },
    async exportExcel() {
      const res = await exportExcel()
      // 参数1: blob 对象
      // 参数2: 文件名
      fileSaver.saveAs(res, '员工信息表.xlsx')
    },
    async hDel(id) {
      // console.log(id)
      // 调用接口删除
      await delEmployee(id)
      // 提示用户
      this.$message.success('删除成功')
      if (this.list.length === 1 && this.q.page > 1) this.q.page--
      // 重新加载
      this.loadEmployees()
    },
    async openRoleDialog(id) {
      // 存储当前点击的员工 id
      this.currentId = id
      // 发请求获取所有可用角色
      this.roles = await getEnableRoles()
      // 发请求获取当前点击的用户所拥有的角色
      const { roleIds } = await getEmployeeDetail(id)
      // 回显: 由于是双向绑定, 赋值给数组就等于是勾选了指定的 checkbox
      this.checkList = roleIds
      // 打开对话框
      this.showRoleDialog = true
    },
    async confirmAssign() {
      await assignRoles({
        id: this.currentId,
        roleIds: this.checkList
      })
      this.showRoleDialog = false
      this.$message.success('分配角色成功')
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}

</style>
